﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

using Xc.DataAccess.DataBases.Core.Models;

namespace Xc.DataAccess.DataBases.Logs.Services
{
    internal class DbLogService<TDbContext> : IDbLogService where TDbContext : DbContext, IDbLog
    {
        private readonly IDbContextFactory<TDbContext> _dbContextFactory;

        public DbLogService(IDbContextFactory<TDbContext> dbContextFactory)
        {
            _dbContextFactory = dbContextFactory;
        }
        /// <summary>
        /// 写日志
        /// </summary>
        public void WriteLines(params Log[] args)
        {
            using (var db = _dbContextFactory.CreateDbContext())
            {
                db.Logs.AddRange(args);
                db.SaveChanges();
            }
        }
        /// <summary>
        /// 获取数据库日志
        /// </summary>
        /// <param name="dtStart"></param>
        /// <param name="dbEnd"></param>
        /// <param name="logLevel"></param>
        /// <returns></returns>
        public IEnumerable<Log> GetLogs(DateTime? dtStart, DateTime? dbEnd, LogLevel? logLevel, string category = null)
        {
            using (var db = _dbContextFactory.CreateDbContext())
            {
                IQueryable<Log> logs = db.Logs;
                if (logLevel.HasValue)
                {
                    logs = logs.Where(p => p.LogLevel == logLevel.Value);
                }
                if (dtStart.HasValue)
                {
                    logs = logs.Where(p => p.DateTime >= dtStart);
                }
                if (dbEnd.HasValue)
                {
                    logs = logs.Where(p => p.DateTime <= dbEnd);
                }
                if (category != null)
                {
                    logs = logs.Where(p => p.Category == category);
                }
                return logs;
            }
        }
        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <returns></returns>
        public IEnumerable<string> GetCategorys(DateTime? dtStart, DateTime? dbEnd)
        {
            using (var db = _dbContextFactory.CreateDbContext())
            {
                IQueryable<Log> logs = db.Logs;
                if (dtStart.HasValue)
                {
                    logs = logs.Where(p => p.DateTime >= dtStart);
                }
                if (dbEnd.HasValue)
                {
                    logs = logs.Where(p => p.DateTime <= dbEnd);
                }
                return logs.Select(p => p.Category).GroupBy(p => p).Select(p => p.Key).ToArray();
            }
        }
    }
}
